package com.dsunsoft.rtu.core.oauth.exception;

import com.dsunsoft.rtu.common.entity.RestCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * 自定义错误信息转换
 *
 * @author ygm
 */
@Slf4j
@Component("customWebResponseExceptionTranslator")
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        log.error("webResponseExceptionTranslator error: ", e);

        int status;
        String errorMessage;
        if (e instanceof InvalidGrantException) {
            status = HttpStatus.UNAUTHORIZED.value();
            errorMessage = RestCode.USER_NAME_OR_PWD_ERROR.getMessage();
        } else if (e instanceof InvalidTokenException) {
            status = HttpStatus.UNAUTHORIZED.value();
            errorMessage = RestCode.USER_LOGIN_EXPIRED.getMessage();
        } else if (e instanceof OAuth2Exception) {
            OAuth2Exception oAuth2Exception = (OAuth2Exception) e;
            status = oAuth2Exception.getHttpErrorCode();
            errorMessage = oAuth2Exception.getMessage();
        } else {
            status = HttpStatus.INTERNAL_SERVER_ERROR.value();
            errorMessage = RestCode.ERROR.getMessage();
        }
        return ResponseEntity.status(status).body(new CustomOauthException(errorMessage));
    }
}